local pb = require "protobuf"
local CMD = require "game_cmd"

local M = {}

local PREFIX = 2

function M.registerFile(szPath)
    pb.register_file(szPath)
end

function M.encode(pbType, msg)
    local szEncoded = pb.encode(pbType, msg)
    local pbLen = string.len(szEncoded)
    local pbTypeLen = string.len(pbType)
    local format = string.format("> i2 c%d c%d", pbTypeLen, pbLen)
    local pack = string.pack(format, pbTypeLen, pbType, szEncoded)
    return pack
end

function M.decode(szEncoded)
    local len = string.len(szEncoded)
    local format = string.format("> i2 c%d", len - 2)
    local cmd_id, body = string.unpack(format, szEncoded)
    print("decode cmd:", cmd_id)

    local pbType = CMD[cmd_id]
    if not pbType then
        return
    end

    local msg = pb.decode(pbType, body)
    return msg, cmd_id
end

function M.encodeAndPack(cmd_id, msg)
    local pbType = CMD[cmd_id]
    if not pbType then
        return
    end

    local szEncoded = pb.encode(pbType, msg)
    local len = string.len(szEncoded)
    local format = string.format(">i%d >i2 c%d", PREFIX, len)
    local pack = string.pack(format, len, cmd_id, szEncoded)
    print("pb len:", len)
    return pack
end

return M
